//============================================================================
// Name        : main.cpp
// Author      : tufeigd
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <forward_list>

#include "net/IoService.h"
#include "net/Acceptor.h"

using namespace std;
using namespace zeus;

struct TestConnection:public ref_count
{
	TcpSocket _socket;
	Buffer _in;
	Buffer _out;

	TestConnection(IoService & io_service)
	:_socket(io_service)
	{
		_in.reserve(1024);
		_out.reserve(1024);
	}
};

typedef ref_ptr<TestConnection> TestConnectionPtr;

void on_new_socket(const TestConnectionPtr & conn,const Error & err);
void read_head(const TestConnectionPtr & conn);
void on_complete_head(const TestConnectionPtr & conn,const Error & err,size_t bytes_transferred);
void read_body(const TestConnectionPtr & conn);
void on_complete_body(const TestConnectionPtr & conn,const Error & err,size_t bytes_transferred);

void on_message(const TestConnectionPtr & conn);


int main()
{
	IoService io;

	Acceptor acceptor(io);

	acceptor.listen(8024);

	TestConnectionPtr conn = new TestConnection(io);

	acceptor.accept(conn->_socket,std::bind(&on_new_socket,conn,std::placeholders::_1));

	io.loop();

	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	return 0;
}


void on_new_socket(const TestConnectionPtr & conn,const Error & err)
{
	printf("%s\n",__FUNCTION__);

//	conn->_socket.enable_reading();

//	conn->_socket.regist();

	read_head(conn);
}

void on_logic_timer()
{
}

void read_head(const TestConnectionPtr & conn)
{
	conn->_socket.read_solid(conn->_in,16,std::bind(&on_complete_head,conn,std::placeholders::_1,std::placeholders::_2));
}

void on_complete_head(const TestConnectionPtr & conn,const Error & err,size_t bytes_transferred)
{

	string data(conn->_in.data());

	cout << "recv data is:" << data << endl;

	read_body(conn);
}

void read_body(const TestConnectionPtr & conn)
{
	conn->_socket.read_solid(conn->_in,32,std::bind(&on_complete_body,conn,std::placeholders::_1,std::placeholders::_2));
}

void on_complete_body(const TestConnectionPtr & conn,const Error & err,size_t bytes_transferred)
{
	on_message(conn);

	conn->_in.clear();

	read_head(conn);
}

void on_message(const TestConnectionPtr & conn)
{
//	Packet packet =  parse_as_packet(buff);
//
//	push_to_logic_queue(packet);
}
